import { Injectable } from "@angular/core";
import { Http, Headers } from "@angular/http";
import { BASEURL } from "shared";

import "rxjs/add/operator/toPromise";

@Injectable()
export class QiniuService {
  private tokenUrl = `${BASEURL}/tokens/qnput`;
  private uploadUrl = "http://upload.qiniu.com";

  private handleError(error: any): Promise<any> {
    console.error("An error occurred", error);
    let desc = error.json().errDesc || "error";
    return Promise.reject(desc);
  }

  constructor(private http: Http) { }

  private getToken() {
    return this.http.get(this.tokenUrl);
  }

  upload(file: any, callback): Promise<any> {
    if (!file) {
      return;
    }
    this.getToken().toPromise().then(data => {
      let f = new FormData();
      // console.info("file: ", file, data.json().token);
      f.append("file", file);
      f.append("token", data.json().token);
      return this.http.post(this.uploadUrl, f, { withCredentials: false })
        .toPromise()
        .then(res => {
          // console.info("qiniu service: ", res.json());
          callback(null, res.json().url);
        })
        .catch(this.handleError);
    }).catch(this.handleError);
  }
}